import os
from .models import *
import json
import datetime
import re
import hashlib
from django.db import connection

'''
fs.remove('problemInfos.json')
fs.remove('specials.json')
fs.remove('tags.json')
'''


def importTags():
    tf = open('data/tags.json', 'r', encoding='utf-8')
    ls = json.load(tf)
    for l in ls:
        t = ProblemTag()
        t.id = l.get('Id')
        t.name = l.get('Name')
        print(t.name)
        t.save()
    tf.close()


def importCCF():
    with open('data/problemInfos.json', 'r', encoding='utf-8') as f:
        fs = json.load(f)

    tags = ProblemTag.objects.all()
    tagDic = {}
    for tag in tags:
        tagDic[tag.name] = tag

    for f in fs:
        with open(os.path.join('data', str(f.get('Id')) + '.json'), 'r', encoding='utf-8') as ff:
            p = json.load(ff)
        np = Problem()
        np.id = p.get('Id')
        np._id = f.get('OldId')
        np.title = p.get('Title')
        np.description = p.get('Description')
        np.input_description = p.get('Input_description')
        np.output_description = p.get('Output_description')
        np.solution = p.get('Solution')
        np.samples = p.get('Samples')
        np.test_case_id = p.get('Test_case_id')
        np.hint = p.get('Hint')
        np.time_limit = p.get('Time_limit')
        np.memory_limit = p.get('Memory_limit')
        np.visible = p.get('Visible')
        np.submission_number = p.get('Submission_number')
        np.accepted_number = p.get('Accepted_number')
        np.difficulty = p.get('Difficulty')
        np.source = p.get('Source')
        np.save()
        for qt in f['Tags']:
            if qt in tagDic:
                np.tags.add(tagDic[qt])
            else:
                t = ProblemTag()
                t.name = qt
                t.save()
                tagDic[t.name] = t
                np.tags.add(tagDic[qt])


def importSpecial():
    with open('data/specials.json', 'r', encoding='utf-8') as f:
        sps = json.load(f)
    for sp in sps:
        s = Special()
        s.id = sp['Id']
        s.title = sp['Title']
        s.description = sp['Description']
        s.problems_count = len(sp['Problems'])
        s.order_num = sp['Order_num']
        s.group_name = sp['Group_name']

        s.save()

        for p in sp['Problems']:
            np = Problem.objects.get(id=p)
            s.problems.add(np)

def initBlog():
    blogtag = BlogTag()
    blogtag.name = '欢迎'
    blogtag.save()

    category = BlogCategory()
    category.name = '初始化'
    category.save()

    blog = Blog()
    blog.title = '欢迎使用'
    blog.content = '这是测试文章，欢迎使用！'
    blog.lead = '这是测试文章，欢迎使用！'
    blog.save()

    blog.tags.add(blogtag)
    blog.categories.add(category)


def importAll():
    importTags()
    importCCF()
    importSpecial()
    initBlog()
